package com.wang.vedio.player;

import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxLookNumberDialog;
import com.wang.vedio.R;
import com.wang.vedio.adapter.index.DetailsCommentAdapter;
import com.wang.vedio.adapter.index.DetailsSuggestionAdapter;
import com.wang.vedio.base.BaseActivity;
import com.wang.vedio.bean.BannerBean;
import com.wang.vedio.bean.DetailsCommentBean;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.entity.LoginBean;
import com.wang.vedio.net.entity.VideoBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.utils.StringUtils;
import com.wang.vedio.utils.statusbar.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PlayerActivity extends BaseActivity {
    @BindView(R.id.video_player)
    StandardGSYVideoPlayer videoPlayer;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_play_count)
    TextView tv_play_count;
    @BindView(R.id.iv_ad)
    ImageView iv_ad;
    @BindView(R.id.rv_suggestion)
    RecyclerView rv_suggestion;
    @BindView(R.id.rv_comment)
    RecyclerView rv_comment;


    @BindView(R.id.searchEdit)
    EditText searchEdit;

    @BindView(R.id.iv_transfer)
    ImageView iv_transfer;

    @BindView(R.id.iv_like)
    ImageView iv_like;

    @BindView(R.id.tv_refresh)
    TextView tv_refresh;

    @BindView(R.id.zheCeng)
    View zheCeng;


    private OrientationUtils orientationUtils;

    private ArrayList<DetailsCommentBean> commentBeans = new ArrayList<>();
    private ArrayList<VideoBean> suggestionBeans = new ArrayList<>();
    private DetailsSuggestionAdapter suggestionAdapter;
    private DetailsCommentAdapter commentAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_player_layout;
    }

    private VideoBean vObj;

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        vObj = (VideoBean) getIntent().getExtras().getSerializable("obj");

        StatusBarUtil.setStatusBar(this, true, R.color.transparent, false, true);
        initVideoPlayer();
        initSuggestionRv();
        initCommentRv();

        if (vObj.getSfsc() == 1) {
            iv_like.setImageResource(R.drawable.love_red);
        } else {
            iv_like.setImageResource(R.drawable.love_normal);
        }
    }

    private void initCommentRv() {
        commentBeans.clear();
        ((SimpleItemAnimator) rv_comment.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        rv_comment.setLayoutManager(linearLayoutManager);
        commentAdapter = new DetailsCommentAdapter(R.layout.item_details_comment, commentBeans);
        rv_comment.setAdapter(commentAdapter);
    }

    private void initSuggestionRv() {
        suggestionBeans.clear();
        ((SimpleItemAnimator) rv_suggestion.getItemAnimator()).setSupportsChangeAnimations(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rv_suggestion.setLayoutManager(gridLayoutManager);
        suggestionAdapter = new DetailsSuggestionAdapter(R.layout.item_suggestion_list, suggestionBeans);
        rv_suggestion.setAdapter(suggestionAdapter);
        suggestionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                getVedioById(suggestionBeans.get(position).getId());
            }
        });
    }

    private void getVedioById(String vedioId) {
        SubscriberOnNextListener<BaseBean<VideoBean>> onNextListener = baseBean -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable("obj", baseBean.getData());
            RxActivityTool.skipActivity(mContext, PlayerActivity.class, bundle);
        };
        Map<String, Object> params = new HashMap<>();
        params.put("id", vedioId);
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getVedioById(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    @Override
    protected void initData() {
        getMemberInfo();
        getBanner();
        getTuiJianList();
        getPingLun();
    }

    private int gycs = -1;
    private void getMemberInfo() {
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            gycs = baseBean.getData().getTodayLookNumber();
            if (baseBean.getData().getTodayLookNumber() == 0) {
                //没有观影次数
                zheCeng.setVisibility(View.VISIBLE);
                showLookNumberDialog();
            }else if(baseBean.getData().getTodayLookNumber() == -100) {
                //VIP观看
                zheCeng.setVisibility(View.VISIBLE);
                showKthyDialog( "您不是会员，不能观看次电影");
            }else {
                videoPlayer.startPlayLogic();
                zheCeng.setVisibility(View.GONE);
                addLookVedioNote();
            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(mContext));
        params.put("id", vObj.getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getPersonCenterInfo(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void addLookVedioNote() {
        SubscriberOnNextListener<BaseBean<List<BannerBean>>> onNextListener = baseBean -> {

        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(mContext));
        params.put("id", vObj.getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().addLookVedioNote(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void getBanner() {
        SubscriberOnNextListener<BaseBean<List<BannerBean>>> onNextListener = baseBean -> {
            Glide.with(this)
                    .load(HttpMethods.BASE_URL + baseBean.getData().get(0).getAdImg())
                    .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(30))))
                    .into(iv_ad);
        };
        Map<String, Object> params = new HashMap<>();
        params.put("adCode", "playBanner");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getBannerByCode(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private int page = 1;

    private void getTuiJianList() {
        SubscriberOnNextListener<BaseBean<List<VideoBean>>> onNextListener = baseBean -> {
            suggestionBeans.clear();
            suggestionBeans.addAll(baseBean.getData());
            suggestionAdapter.notifyDataSetChanged();
        };
        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", page + "");
        params.put("typeName", vObj.getTypeName() + "");
        params.put("id", vObj.getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getDetailTuiJianList(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void getPingLun() {
        SubscriberOnNextListener<BaseBean<List<DetailsCommentBean>>> onNextListener = baseBean -> {
            commentBeans.clear();
            commentBeans.addAll(baseBean.getData());
            commentAdapter.notifyDataSetChanged();
        };
        Map<String, Object> params = new HashMap<>();
        params.put("id", vObj.getId());
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getPingLunList(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void showLookNumberDialog() {
        RxLookNumberDialog dialog = new RxLookNumberDialog(this);
        dialog.getBtn_close().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.getBtn1().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //充会员
                RxActivityTool.skipActivity(mContext, VipActivity.class);
            }
        });
        dialog.getBtn2().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //邀请好友赚会员
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                RxActivityTool.skipActivity(mContext, InviteFriendActivity.class, bundle);
            }
        });
        dialog.show();
    }


    private void initVideoPlayer() {
        tv_title.setText(vObj.getTitle());
        tv_time.setText(vObj.getVedioSeconds());
        tv_play_count.setText(vObj.getPlayNum() + "次");

        videoPlayer = (StandardGSYVideoPlayer) findViewById(R.id.video_player);
        videoPlayer.setUp(HttpMethods.BASE_URL + vObj.getVedioPath(), true, "");
        //增加封面
        ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

        Glide.with(imageView)
                .load(HttpMethods.BASE_URL + vObj.getVedioFmImg())
                .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(30))))
                .into(imageView);


        videoPlayer.setThumbImageView(imageView);
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.GONE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.GONE);
        //设置旋转
        orientationUtils = new OrientationUtils(this, videoPlayer);
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orientationUtils.setIsLand(0);
                orientationUtils.resolveByClick();
                videoPlayer.startWindowFullscreen(mContext, false, true);
            }
        });
        videoPlayer.setSeekRatio(15);
        videoPlayer.setNeedShowWifiTip(false);
        videoPlayer.setLooping(true);
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(false);
        videoPlayer.setAutoFullWithSize(true);
        videoPlayer.getBackButton().setVisibility(View.GONE);
    }


    private void savePingLun() {
        SubscriberOnNextListener<BaseBean<DetailsCommentBean>> onNextListener = baseBean -> {
            if("您还不是会员".equals(baseBean.getMessage())){
                showKthyDialog("您不是会员，不能评价");
                return;
            }
            commentBeans.add(0, baseBean.getData());
            commentAdapter.notifyDataSetChanged();
            searchEdit.setText("");
        };
        DetailsCommentBean params = new DetailsCommentBean();
        params.setMemberId(SharedHelper.readId(mContext));
        params.setVideoId(vObj.getId());
        params.setMemberId(SharedHelper.readId(mContext));
        params.setContent(searchEdit.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().savePingLun(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    private void addCollect() {
        SubscriberOnNextListener<BaseBean<String>> onNextListener = baseBean -> {
            vObj.setCollectNum(baseBean.getData());
            if ("1".equals(vObj.getCollectNum())) {
                iv_like.setImageResource(R.drawable.love_red);
                RxToast.normal("已收藏");
            } else {
                iv_like.setImageResource(R.drawable.love_normal);
                RxToast.normal("已取消");
            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(mContext));
        params.put("vedioId", vObj.getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().addVidoCollect(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }

    @Override
    public void onBackPressed() {
        //先返回正常状态
//        if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//            videoPlayer.getFullscreenButton().performClick();
//            return;
//        }
        Configuration cf = mContext.getResources().getConfiguration();
        if (cf.orientation == cf.ORIENTATION_LANDSCAPE) {
            videoPlayer.getFullscreenButton().performClick();
        } else if (cf.orientation == cf.ORIENTATION_PORTRAIT) {
            //释放所有
            videoPlayer.setVideoAllCallBack(null);
        }
        super.onBackPressed();
    }

    private void showKthyDialog(String title) {
        RxLookNumberDialog dialog = new RxLookNumberDialog(this);
        dialog.getTishiTv().setText(title);
        dialog.getBtn1().setText("立即开通");
        dialog.getBtn2().setText("暂不开通");
        dialog.getBtn_close().setVisibility(View.GONE);
        dialog.getBtn1().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxActivityTool.skipActivity(mContext,VipActivity.class);
                dialog.dismiss();
            }
        });
        dialog.getBtn2().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //邀请好友赚会员
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @OnClick({R.id.iv_transfer, R.id.iv_like, R.id.tv_refresh, R.id.zheCeng})
    public void onClick(View v) {
        if (v.getId() == R.id.iv_transfer) {
            if (StringUtils.isEmpty(searchEdit.getText().toString())) {
                RxToast.normal("评论不能是空");
                return;
            }
            savePingLun();
        } else if (v.getId() == R.id.iv_like) {
            addCollect();
        } else if (v.getId() == R.id.tv_refresh) {
            page++;
            getTuiJianList();
        } else if (v.getId() == R.id.zheCeng) {
            if(gycs == -100){
                //VIP观看
                showKthyDialog( "您不是会员，不能观看次电影");
            }else{
                showLookNumberDialog();
            }
        }
    }
}
